<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading" @selection-change="handleSelectionChange">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button size="mini" v-if="checkPermission(['warehouseOut:del'])" @click="handleDeleteWarehouseOut()" type="danger"
            :disabled="multipleSelection.length === 0">删除</el-button>
        </div>
        <div class="toolbar-search">
          <en-table-search @search="searchEvent" @advancedSearch="advancedSearchEvent" placeholder="请输入出库单编号" advanced
            advancedWidth="465">
            <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm" label-width="90px">
                <el-form-item label="订单编号">
                  <el-input v-model="advancedForm.order_sn" clearable placeholder="请输入订单编号"></el-input>
                </el-form-item>
                <el-form-item label="所属部门">
                  <el-cascader v-model="advancedForm.dept_id" :options="deptList" :props="{
                    label: 'name',
                    value: 'id',
                    emitPath: false,
                    checkStrictly: true
                  }" clearable></el-cascader>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="advancedForm.status">
                    <el-option key="WAIT_AUDIT" label="待审核" value="WAIT_AUDIT" />
                    <el-option key="WAIT_SHIP" label="待发货" value="WAIT_SHIP" />
                    <el-option key="SHIP" label="已发货" value="SHIP" />
                  </el-select>
                </el-form-item>
                <el-form-item label="时间">
                  <el-date-picker v-model="advancedForm.warehouseOut_time_range" type="daterange" align="center"
                    :editable="false" unlink-panels :clearable="false" :default-time="['00:00:00', '23:59:59']"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="timestamp"
                    :picker-options="{ disabledDate(time) { return time.getTime() - 1 >= new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime() + 86400000 - 1 }, shortcuts: MixinPickerShortcuts }">
                  </el-date-picker>
                </el-form-item>
              </el-form>
            </template>
          </en-table-search>
        </div>
      </div>
      <template slot="table-columns">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sn" label="出库单编号">
          <template slot-scope="scope">
            <router-link
              v-if="checkPermission(['orderOutbound'])"
              style="color: #409eff;"
              :to="{ name: 'orderOutboundDetail', params: { id: scope.row.id } }">
              {{ scope.row.sn }}
            </router-link>
            <span v-else>{{scope.row.sn}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="out_time" label="出库日期">
          <template slot-scope="scope">{{ scope.row.out_time | unixToDate }}</template>
        </el-table-column>
        <el-table-column prop="dept_name" label="所属部门" />
        <el-table-column prop="warehouse_name" label="仓库" />
<!--        <el-table-column prop="distribution_name" label="销售经理" />-->
        <el-table-column prop="consignee" label="提货人" />
<!--        <el-table-column prop="audit_by" label="审核人" />-->
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">{{ statusFilter(scope.row.status) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
<!--            <el-button size="mini" v-if="scope.row.allowable.audit && checkPermission(['warehouseOut:audit'])" type="success"-->
<!--              @click="handleAuditDialog(scope.row)">审核</el-button>-->
            <el-button size="mini" v-if="scope.row.allowable.ship && checkPermission(['warehouseOut:send'])" type="success"
              @click="handleSendWarehouseOut(scope.row)">发货</el-button>
            <el-button type="primary" v-if="checkPermission(['warehouseOut:print'])" size="mini"
              @click="handlePrintWarehouseOutDialog(scope.row)">打印</el-button>
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
      </el-pagination>
    </en-table-layout>

    <el-dialog title="出库单表" :visible.sync="dialogVisible" width="940px" center>
      <el-button size="mini" type="primary" @click="handlePrintWarehouseOut" class="print">打印</el-button>
      <div id="deliverySheet" style="width:900px">
        <div class="tips-t">
          <div>
            仓库名称编码:<span v-if="warehouseOutForm.dept_name">{{ warehouseOutForm.dept_name }}部门</span><span
              v-if="warehouseOutForm.warehouse_name">{{ warehouseOutForm.warehouse_name }}仓库</span>
          </div>
          <div>
            日期:{{ warehouseOutForm.out_time | unixToDateStr }}
          </div>
          <div>
            编号:{{ warehouseOutForm.sn }}
          </div>
        </div>
        <div class="tips-t" style="margin:0 20px">
          <div>
            用户电话:{{ warehouseOutForm.member_mobile }}
          </div>
          <div>
            用户姓名:{{ warehouseOutForm.member_real_name }}
          </div>
          <div>
<!--            用户收货地址:{{ warehouseOutForm.ship_addr }}-->
          </div>
        </div>
        <el-table :data="warehouseOutForm.item_list" border :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center', background: '#f4f4f4' }" style="width: 100%; margin-top: 20px;">
          <el-table-column label="产品编码">
            <template slot-scope="scope">
              {{ scope.row.product_sn }}
            </template>
          </el-table-column>
          <el-table-column label="产品名称">
            <template slot-scope="scope">
              {{ scope.row.product_name }}
            </template>
          </el-table-column>
          <el-table-column label="规格型号">
            <template slot-scope="scope">
              {{ scope.row.product_specification }}
            </template>
          </el-table-column>
          <el-table-column label="数量">
            <template slot-scope="scope">
              {{ scope.row.out_num }}
            </template>
          </el-table-column>
        </el-table>
        <div class="tips-t">
          <div>
            提货人:{{ warehouseOutForm.consignee }}
          </div>
          <div>
            客户订单号:{{ warehouseOutForm.order_sn_list ? formatFilter(warehouseOutForm.order_sn_list) : '' }}
          </div>
          <div>
            制单人:{{ warehouseOutForm.create_by }}
          </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="订单发货" :visible.sync="dialogSendVisible" width="450px">
      <el-form :model="warehouseOutForms" ref="warehouseOutForms" label-width="120px">
        <el-form-item label="出库单号:" prop="name">
          {{ warehouseOutForms.sn }}
        </el-form-item>
        <el-form-item label="订单编号:" prop="sn">
          <span v-if="warehouseOutForms.order_sn_list">{{ formatFilter(warehouseOutForms.order_sn_list) }}</span>
        </el-form-item>
        <el-form-item label="配送方式:" prop="category_id">
          <el-radio v-model="warehouseOutForms.delivery_type" :label="'express'" :disabled="true">物流配送</el-radio>
          <el-radio v-model="warehouseOutForms.delivery_type" :label="'self_pick'" :disabled="true">自提</el-radio>
        </el-form-item>
        <span v-if="warehouseOutForms.delivery_type === 'self_pick'">
          <el-form-item label="自提点:" prop="store_id">
            {{ warehouseOutForms.store_name }}
          </el-form-item>
          <el-form-item label="物流费用:" prop="freight_price">
            <el-input v-model="warehouseOutForms.freight_price" type="number"
              oninput="value=parseInt(value.replace(/[^\d]/g,''))" :minlength="1" :maxlength="20" clearable
              placeholder="请输入物流费用"></el-input>
          </el-form-item>
          <el-form-item label="提货人:" prop="consignee">
            <el-input v-model="warehouseOutForms.consignee" :minlength="1" :maxlength="20" clearable
              placeholder="请输入提货人"></el-input>
          </el-form-item>
        </span>
        <span v-else>
          <el-form-item label="物流公司:" prop="logistics_company_id">
            <el-select v-model="warehouseOutForms.logistics_company_id">
              <el-option v-for="item in expressCompanyList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="物流单号:" prop="tracking_number">
            <el-input v-model="warehouseOutForms.tracking_number" :minlength="1" :maxlength="20" clearable
              placeholder="请输入物流单号"></el-input>
          </el-form-item>
          <el-form-item label="物流费用:" prop="freight_price">
            <el-input v-model="warehouseOutForms.freight_price" type="number"
              oninput="value=parseInt(value.replace(/[^\d]/g,''))" :minlength="1" :maxlength="20" clearable
              placeholder="请输入物流费用"></el-input>
          </el-form-item>
          <el-form-item label="提货人:" prop="consignee">
            <el-input v-model="warehouseOutForms.consignee" :minlength="1" :maxlength="20" clearable
              placeholder="请输入提货人"></el-input>
          </el-form-item>
        </span>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogSendVisible = false">取 消</el-button>
        <el-button type="primary" @click="warehouseOutShip">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="审核" :visible.sync="auditVisible" width="500px" center>
      <span>请选择审核状态：</span>
      <el-radio v-model="auditStatus" label="AUDIT_PASS">通过</el-radio>
      <el-radio v-model="auditStatus" label="AUDIT_REJECT">驳回</el-radio>
      <div class="btn-box">
        <el-button type="" @click="auditVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAuditWarehouseOut">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API_Order from '@/api/order'
import Print from 'print-js'
import * as API_Setting from '@/api/setting'
import { Foundation } from '~/ui-utils'
export default {
  name: 'warehouseOut',
  data() {
    return {
      deptList: [],
      expressCompanyList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10
      },
      // 高级搜索数据
      advancedForm: {},
      // 列表数据
      tableData: '',
      dialogVisible: false,
      dialogSendVisible: false,
      // 当前已选择的行
      multipleSelection: [],
      warehouseOutForm: {},
      warehouseOutForms: {},
      // 审核弹窗显隐
      auditVisible: false,
      // 当前操作审核ID
      auditId: '',
      // 审核状态
      auditStatus: 'AUDIT_PASS'
    }
  },
  mounted() {
    this.GET_WarehouseOutList()
    this.GET_DeptList()
    this.GET_ExpressCompanyList()
  },
  watch: {
    $route: function({ query }) {
      this.params.page_no = 1
      this.GET_WarehouseOutList()
    }
  },
  methods: {
    /** 审核操作 */
    handleAuditDialog(row) {
      this.auditVisible = true
      this.auditId = row.id
    },
    /** 审核提交 */
    handleAuditWarehouseOut() {
      API_Order.handleAuditWarehouseOut(this.auditId, { status: this.auditStatus }).then(response => {
        this.$message.success('提交成功！')
        this.auditVisible = false
        this.GET_WarehouseOutList()
      })
    },
    GET_ExpressCompanyList() {
      API_Order.getExpressCompanyList({ page_no: 1, page_size: 9999 }).then(response => {
        this.expressCompanyList = response.data
      })
    },
    warehouseOutShip() {
      API_Order.warehouseOutShip(this.warehouseOutForms).then(response => {
        this.$message.success('发货成功！')
        this.GET_WarehouseOutList()
        this.dialogSendVisible = false
      })
    },
    formatFilter(val) {
      return val.join(',')
    },
    /** 出库单状态 */
    statusFilter(val) {
      switch (val) {
        case 'WAIT_SHIP':
          return '待发货'
        case 'WAIT_AUDIT':
          return '待发货'
        case 'SHIP':
          return '已发货'
        default:
          return ''
      }
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
      })
    },
    /** 打印对账详情 */
    handlePrintWarehouseOut() {
      Print({
        printable: 'deliverySheet',
        type: 'html',
        targetStyles: ['*'],
        ignoreElements: ['no-logs', 'goods-image', 'no-btn']
      })
    },
    handleDeleteWarehouseOut() {
      this.$confirm('确定要删除这些出库单吗？', '提示', { type: 'warning' }).then(() => {
        const ids = this.multipleSelection.map(item => item.id)
        API_Order.deleteWarehouseOut(ids).then(() => {
          this.$message.success('删除成功！')
          this.GET_WarehouseOutList()
        })
      }).catch(() => { })
    },
    /** 多选改变 */
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_WarehouseOutList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_WarehouseOutList()
    },

    /** 发货 */
    handleSendWarehouseOut(row) {
      this.warehouseOutForms = row
      this.dialogSendVisible = true
    },
    /** 打印出库单 */
    handlePrintWarehouseOutDialog(row) {
      this.GET_WarehouseOutDetail(row.id)
    },
    /** 获取出库单详情页面数据 */
    GET_WarehouseOutDetail(id) {
      API_Order.getWarehouseOutInfo(id).then(response => {
        this.warehouseOutForm = response
        if (response.product_list && response.product_list.length) {
          var str = ''
          response.product_list.forEach(function(i) {
            str += i.product_name + '、'
          })
        }
        this.warehouseOutForm.illustrate = str
        this.dialogVisible = true
      })
    },
    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        sn: data
      }
      Object.keys(this.advancedForm).forEach((key) => delete this.params[key])
      this.params.page_no = 1
      this.GET_WarehouseOutList()
    },
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm
      }
      delete this.params.start_time
      delete this.params.end_time
      if (this.advancedForm.warehouseOut_time_range) {
        this.params.start_time = parseInt(Number(this.advancedForm.warehouseOut_time_range[0]) / 1000)
        this.params.end_time = parseInt(Number(this.advancedForm.warehouseOut_time_range[1]) / 1000)
      }
      delete this.params.warehouseOut_time_range
      this.params.page_no = 1
      this.GET_WarehouseOutList()
    },
    /** 获取出库单列表 */
    GET_WarehouseOutList() {
      this.loading = true
      API_Order.getWarehouseOutList(this.params).then(response => {
        this.loading = false
        this.tableData = response
      }).catch(() => { this.loading = false })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.print {
  margin-left: 790px;
}
.btn-box {
  text-align: center;
  margin: 30px 0 10px;
}
.tips-t {
  display: flex;
  padding: 10px 0;

  div {
    flex: 1;
    text-align: center;
  }
}

.tips-f {
  padding: 20px 0;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
